package com.ff.javamonkey.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

import com.ff.javamonkey.R;

public class ServerActivity extends Activity {
	// Debugging
	private final String TAG = "ServerActivity";
	
	// UI Components
	private TextView txtServerStatus;
	private TextView txtServerStream;
	
	// Default IP
	public static String SERVER_IP = "10.0.2.15";
	
	// Designate a Port
	public static final int SERVER_PORT = 22;
	
	private Handler handler = new Handler();
	
	private ServerSocket serverSocket;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_server);
		txtServerStatus = (TextView)findViewById(R.id.txtServerStatus);
		txtServerStream = (TextView)findViewById(R.id.txtServerStream);
		
		SERVER_IP = getLocalIpAddress();
		Log.i(TAG, SERVER_IP);
		
		Thread fst = new Thread(new ServerThread());
		fst.start();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		try {
			serverSocket.close();
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	public class ServerThread implements Runnable {

		public void run() {
			try {
				if (SERVER_IP != null) {
					handler.post(new Runnable() {
						public void run() {
							txtServerStatus.setText("Listening on IP: " + SERVER_IP);
						}
					});
					serverSocket = new ServerSocket(SERVER_PORT);
					while (true) {
						// Listen for incoming clients
						Socket client = serverSocket.accept();
						handler.post(new Runnable() {
							public void run() {
								txtServerStatus.setText("Connected");
							}
						});
						try {
							BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
							String line = null;
							while ((line = in.readLine()) != null) {
								Log.i(TAG, line);
								handler.post(new Runnable() {
									public void run() {
										//txtServerStream.append(line);
									}
								});
							}
							break;
						}
						catch (Exception e) {
							handler.post(new Runnable() {
								public void run() {
									txtServerStatus.setText("Connection interrupted. Please reconnect.");
								}
							});
							e.printStackTrace();
						}
					}
				}
				else {
					handler.post(new Runnable() {
						public void run() {
							txtServerStatus.setText("Could not detect internet connection.");
						}
					});
				}
			}
			catch (Exception ex) {
				handler.post(new Runnable() {
					public void run() {
						txtServerStatus.setText("Error.");
					}
				});
				ex.printStackTrace();
			}
		}
	}
	
	// Gets the IP Address on the phone's network
	private String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en =
				NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				Log.i(TAG, intf.getName());
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); 
					enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		}
		catch (SocketException ex) {
			Log.e(TAG, ex.toString());
		}
		return null;
	}
}
